package com.zrkizzy.seckill.handler;

import com.zrkizzy.seckill.enums.HttpStatusEnum;
import com.zrkizzy.seckill.exception.GlobalException;
import com.zrkizzy.seckill.exception.NoLoginException;
import com.zrkizzy.seckill.vo.common.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 *
 * @author zhangrongkang
 * @since 2023/3/21
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(NoLoginException.class)
    public Result repeatLoginExceptionHandler(NoLoginException e) {
        // 返回用户未登录错误
        return Result.error(e.getHttpStatusEnum());
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        // 如果当前发生的异常是全局异常的子类
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            // 直接返回前端对应的错误信息
            return Result.error(ex.getHttpStatusEnum());
        }
        // 如果当前异常为绑定异常
        if (e instanceof BindException) {
            // 强转为绑定异常
            BindException ex = (BindException) e;
            Result result = Result.error(HttpStatusEnum.LOGIN_ERROR);
            result.setMessage("参数校验异常：" + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        // 抛出默认的异常
        return Result.error(HttpStatusEnum.ERROR);
    }

}
